package controller

import (
	"digital/server/common"
	"digital/server/model"
	"digital/server/response"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/jinzhu/gorm"
	"log"
	"net/http"
	"strconv"
	"time"
)

func GetDetail(ctx *gin.Context) {
	DB := common.GetDB()
	account := ctx.Query("account")
	var user model.User // 替换为你的User结构体类型
	result := DB.Where("uid = ?", account).First(&user)
	if result.Error != nil {
		response.Response(ctx, http.StatusInternalServerError, 500, nil, "查询用户信息时发生错误!")
		return
	}

	var honors []model.Honor
	result = DB.Where("uid = ?", user.UID).Find(&honors)
	if result.Error != nil {
		response.Response(ctx, http.StatusInternalServerError, 500, nil, "查询荣誉信息时发生错误!")
		return
	}

	detail := model.Detail{
		Account:     user.UID,
		Intro:       user.Intro,
		Phone:       user.Phone,
		Gender:      user.Gender,
		Campus:      user.Campus,
		Email:       user.Email,
		BackupEmail: user.BackupEmail,
		Honors:      honors,
	}
	fmt.Println("gender:", user.Gender)

	response.Success(ctx, gin.H{"detail": detail}, "个人信息获取成功!")

}

func SaveUserProfile(ctx *gin.Context) {
	db := common.GetDB()
	account := ctx.PostForm("account")
	genderStr := ctx.PostForm("gender")
	intro := ctx.PostForm("intro")
	campus := ctx.PostForm("campus")
	phone := ctx.PostForm("phone")
	email := ctx.PostForm("email")
	backEmail := ctx.PostForm("backEmail")
	gender, err := strconv.Atoi(genderStr)
	if err != nil {
		response.Response(ctx, http.StatusBadRequest, 422, nil, "性别转换失败！")
		return
	}
	if account == "" {
		response.Response(ctx, http.StatusInternalServerError, 500, nil, "获取账号失败!")
		return
	}
	fmt.Println("account:", account)
	fmt.Println("email:", email)
	fmt.Println("Campus:", campus)
	fmt.Println("Phone:", phone)
	fmt.Println("Gender:", gender)
	fmt.Println("Intro:", intro)
	fmt.Println("BackupEmail:", backEmail)
	var existingUser model.User
	if err := db.First(&existingUser, "uid = ?", account).Error; err != nil {
		if err == gorm.ErrRecordNotFound {
			response.Response(ctx, http.StatusInternalServerError, 500, nil, "找不到用户信息!")
			return
		}
		return
	}
	if err := db.Model(&existingUser).Where("uid = ?", account).Updates(map[string]interface{}{
		"gender":      gender,
		"intro":       intro,
		"campus":      campus,
		"phone":       phone,
		"email":       email,
		"backupemail": backEmail,
	}).Error; err != nil {
		response.Response(ctx, http.StatusInternalServerError, 500, nil, "保存用户信息失败!")
		return
	}
	ctx.JSON(http.StatusOK, gin.H{"message": "Profile saved successfully"})
}

func DeleteHonor(ctx *gin.Context) {
	fmt.Println("deleteing xxxxxxxxxx")
	db := common.GetDB()
	account := ctx.Query("account")
	honorID := ctx.Query("honorID")
	fmt.Println("account:", account)
	fmt.Println("honorid:", honorID)
	var honor model.Honor
	result := db.Where("id = ? AND uid = ?", honorID, account).Delete(&honor)
	if result.Error != nil {
		ctx.JSON(http.StatusInternalServerError, gin.H{"error": "数据库错误"})
		return
	}

	if result.RowsAffected == 0 {
		ctx.JSON(http.StatusNotFound, gin.H{"error": "未找到该荣誉记录"})
		return
	}
	ctx.JSON(http.StatusOK, gin.H{"message": "Honor record deleted successfully"})
}

func SaveHonor(ctx *gin.Context) {
	db := common.GetDB()
	account := ctx.PostForm("account")
	honortitle := ctx.PostForm("title")
	honorTime := ctx.PostForm("startTime")
	parsedTime, err := time.Parse("2006-01-02 15:04:05", honorTime)
	if err != nil {
		ctx.JSON(http.StatusBadRequest, gin.H{"error": "Invalid date format"})
		return
	}
	parsedTime = parsedTime.Truncate(24 * time.Hour)
	userid, err := strconv.Atoi(account)
	if err != nil {
		response.Response(ctx, http.StatusBadRequest, 422, nil, "账号转换失败！")
		return
	}
	honor := model.Honor{
		UserID:    userid,
		Title:     honortitle,
		StartTime: parsedTime,
	}
	fmt.Println("honor", honor)
	if err := db.Create(&honor).Error; err != nil {
		ctx.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to save honor record"})
		return
	}
	response.Success(ctx, gin.H{"honorID": honor.HonorID}, "荣誉记录添加成功！")
	fmt.Println("honorID", honor.HonorID)
}

func GetApplies(ctx *gin.Context) {
	DB := common.GetDB()
	account := ctx.Query("account")
	fmt.Println("account", account)

	var applies []model.Apply
	result := DB.Where("uid = ?", account).Find(&applies)
	if result.Error != nil {
		response.Response(ctx, http.StatusInternalServerError, 500, nil, "查询申请记录时发生错误!")
		return
	}

	var applyWithApprovers []model.Apply_to_User
	for _, apply := range applies {
		var approver1Name, approver2Name, approver3Name string

		if *apply.Approver1 != 0 {
			var approver1 model.User
			if err := DB.Where("uid = ?", apply.Approver1).First(&approver1).Error; err == nil {
				approver1Name = approver1.Uname
			}
		}

		if *apply.Approver2 != 0 {
			var approver2 model.User
			fmt.Println("apply.Approver2", apply.Approver2)
			if err := DB.Where("uid = ?", apply.Approver2).First(&approver2).Error; err == nil {
				approver2Name = approver2.Uname
			}
		}

		if *apply.Approver3 != 0 {
			var approver3 model.User
			if err := DB.Where("uid = ?", apply.Approver3).First(&approver3).Error; err == nil {
				approver3Name = approver3.Uname
			}
		}

		applyWithApprovers = append(applyWithApprovers, model.Apply_to_User{
			ID:             apply.ID,
			Apply_ID:       apply.Apply_ID,
			UserID:         apply.UserID,
			Kind:           apply.Kind,
			Approval_State: apply.Approval_State,
			Title:          apply.Title,
			ApplyTime:      apply.ApplyTime,
			Approver1_Name: approver1Name,
			Approver2_Name: approver2Name,
			Approver3_Name: approver3Name,
			ApprovalDate1:  getNullableTime(*apply.ApprovalDate1),
			ApprovalDate2:  getNullableTime(*apply.ApprovalDate2),
			ApprovalDate3:  getNullableTime(*apply.ApprovalDate3),
		})
	}

	response.Success(ctx, gin.H{"apply": applyWithApprovers}, "申请记录获取成功!")
}

// 活动记录
func GetActivityApplies(ctx *gin.Context) {
	DB := common.GetDB()
	account := ctx.Query("account")
	fmt.Println("account", account)

	var applies []model.ActivityApply
	result := DB.Where("UID = ?", account).Find(&applies)
	if result.Error != nil {
		response.Response(ctx, http.StatusInternalServerError, 500, nil, "查询活动时发生错误!")
		return
	}

	var activityapply []model.ActivityApplyToUser
	for _, apply := range applies {
		var activity model.Activity
		if err := DB.Where("id = ?", apply.Aid).First(&activity).Error; err == nil {
			activityapply = append(activityapply, model.ActivityApplyToUser{
				ID:            apply.ID,
				Aid:           apply.Aid,
				SID:           apply.SID,
				ApplyTime:     apply.ApplyTime,
				StartTime:     activity.Stime,
				EndTime:       activity.Etime,
				Result:        apply.Result,
				ActivityState: activity.State,
				Title:         activity.ATitle,
				Place:         activity.Place,
			})
		}
	}
	response.Success(ctx, gin.H{"apply": activityapply}, "活动记录获取成功!")
}

func getNullableTime(t time.Time) *time.Time {
	if t.IsZero() {
		return nil
	}
	return &t
}

// 收藏的活动
func GetCollectedActivities(ctx *gin.Context) {
	account := ctx.Query("uid")
	fmt.Println("个人中心收藏活动")
	DB := common.GetDB()
	var collectedActivities []model.ActivityCollection
	result := DB.Where("uid = ?", account).Find(&collectedActivities)
	if result.Error != nil {
		response.Response(ctx, http.StatusInternalServerError, 500, nil, "查询收藏活动时发生错误!")
		return
	}

	db := common.GetDB()
	var activities []model.Activity
	for _, activity := range collectedActivities {
		var a []model.Activity
		err := db.Where("id=?", activity.Aid).First(&a).Error
		if err != nil {
			response.Response(ctx, http.StatusBadRequest, 400, nil, "发生错误，请重试")
			log.Println("err:", err)
			return
		}
		activities = append(activities, a...)
	}
	//判断活动举办的社团名称
	dB := common.GetDB()

	var clubNames []string
	for _, activity := range activities {
		var clubs []model.Club
		err1 := dB.Where("id=?", activity.Cid).First(&clubs).Error
		if err1 != nil {
			response.Response(ctx, http.StatusBadRequest, 400, nil, "发生错误，请重试")
			log.Println("err1:", err1)
			return
		}
		for _, club := range clubs {
			clubNames = append(clubNames, club.Cname)
		}
	}
	collected := make([]int, len(activities))

	for i := range collected {
		collected[i] = 1
	}
	response.Success(ctx, gin.H{"activities": activities, "clubs": clubNames, "collected": collected}, "收藏活动获取成功!")
}

// 收藏的社团
func GetCollectedClubs(ctx *gin.Context) {
	account := ctx.Query("uid")
	print(account)
	DB := common.GetDB()
	var collectedClubs []model.ClubCollection
	result := DB.Where("uid = ?", account).Find(&collectedClubs)
	if result.Error != nil {
		response.Response(ctx, http.StatusInternalServerError, 500, nil, "查询收藏社团时发生错误!")
		return
	}

	db := common.GetDB()
	var clubs []model.ClubWithImage
	for _, club := range collectedClubs {

		var c model.Club
		err := db.Where("id=?", club.Cid).First(&c).Error
		if err != nil {
			response.Response(ctx, http.StatusBadRequest, 400, nil, "获取收藏的社团错误，请重试")
			log.Println("err:", err)
			return
		}

		var tmp model.CImage
		err1 := db.Where("Cid=? AND Main=?", club.Cid, 1).First(&tmp).Error
		if err1 != nil {
			response.Response(ctx, http.StatusBadRequest, 400, nil, "获取社团封面错误，请重试")
			log.Println("err1:", err1)
			return
		}
		clubimage := model.ClubWithImage{
			Club:  c,
			Image: tmp.Path,
		}
		clubs = append(clubs, clubimage)
	}

	collected := make([]int, len(clubs))
	for i := range collected {
		collected[i] = 1
	}
	response.Success(ctx, gin.H{"clubs": clubs, "collected": collected}, "收藏社团获取成功!")
}

// 加入的社团
func GetJoinedClubs(ctx *gin.Context) {
	account := ctx.Query("uid")
	DB := common.GetDB()
	var joinedClubs []model.UserClub
	result := DB.Where("UID = ? ", account).Where("QTime IS NULL").Find(&joinedClubs)
	if result.Error != nil {
		response.Response(ctx, http.StatusInternalServerError, 500, nil, "查询加入社团时发生错误!")
		return
	}

	db := common.GetDB()
	var clubs []model.ClubWithImage
	for _, club := range joinedClubs {
		var c model.Club
		err := db.Where("id=?", club.Cid).First(&c).Error
		if err != nil {
			response.Response(ctx, http.StatusBadRequest, 400, nil, "查询社团信息发生错误，请重试")
			log.Println("err:", err)
			return
		}
		var tmp model.CImage
		err1 := db.Where("Cid=? AND Main=?", club.Cid, 1).Find(&tmp).Error
		if err1 != nil {
			response.Response(ctx, http.StatusBadRequest, 400, nil, "查询社团封面发生错误，请重试")
			log.Println("err1:", err1)
			return
		}
		clubimage := model.ClubWithImage{
			Club:  c,
			Image: tmp.Path,
		}
		clubs = append(clubs, clubimage)
	}
	response.Success(ctx, gin.H{"clubs": clubs}, "所在社团获取成功!")
}
